package com.weepal.pavement.mqtt.demo.config.dataSource;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;

@Aspect
public class DynaDataSourceAspect {
    //只切自定义的@TargetSource注解
    @Pointcut("@annotation(com.weepal.pavement.mqtt.demo.config.dataSource.TargetSource)")
    public void dataSourcePointCut() {

    }

    //将@TargetSource的值赋值，执行完后将值清除
    @Around("dataSourcePointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        TargetSource annotation = getAnnotation(joinPoint);
        String value = annotation.value();
        DataSourceThreadLocal.setDatasources(value);
        try {
            return joinPoint.proceed();
        } finally {
            DataSourceThreadLocal.removeDatasources();
        }
    }

    //获取注解对象
    private TargetSource getAnnotation(ProceedingJoinPoint joinPoint) {
        Class<?> aClass = joinPoint.getTarget().getClass();
        TargetSource annotation = aClass.getAnnotation(TargetSource.class);
        if (null != annotation) {
            return annotation;
        }
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        return signature.getMethod().getAnnotation(TargetSource.class);
    }
}
